/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
// 思路： 后序遍历，可以得到每个节点高度
var isBalanced = function(root) {
    let dep = [0];
    dfs(root, 0, dep);

    let i=dep.length-1;
    for(;i>1;i--){
        if(Math.abs(dep[i]-dep[i-1])>1)return false;
    }

    //console.log("final",dep[0]);

    if(dep[0]===1)return false;
    return true;
};

function dfs(node, height, dep) {
    if(dep[0]===1)return 0;
    if(!node){
        return height;
    }else{
        let h1 = dfs(node.left, height+1, dep);
        let h2 = dfs(node.right, height+1, dep);

        //console.log("#",node.val,h1,h2);
        if(Math.abs(h1-h2)>1)dep[0] = 1;

        return h1>h2?h1:h2;
    }
}